package leetcode.code1882;

import java.util.PriorityQueue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int[] assignTasks(int[] servers, int[] tasks) {
		PriorityQueue<int[]> avalable = new PriorityQueue<>((a, b) -> {
			if (a[1] != b[1]) {// 服务器权重
				return a[1] - b[1];
			}
			return a[0] - b[0];// 下标
		});
		for (int i = 0; i < servers.length; i++) {
			avalable.add(new int[] { i, servers[i], 0 });
		}
		PriorityQueue<int[]> used = new PriorityQueue<>((a, b) -> {
			if (a[2] != b[2]) {// 0 空闲时间
				return a[2] - b[2];
			}
			if (a[1] != b[1]) {// 服务器权重
				return a[1] - b[1];
			}
			return a[0] - b[0];// 下标
		});
		int len = tasks.length;
		int[] ans = new int[len];
		for (int i = 0, time = 0; i < len; i++) {
			if (avalable.isEmpty()) {
				time = used.peek()[2];
			}
			while (!used.isEmpty() && used.peek()[2] <= time) {
				avalable.add(used.poll());
			}
			int t = tasks[i];
			int[] server = avalable.poll();
			int val = server[1], idx = server[0];
			ans[i] = idx;
			used.add(new int[] { idx, val, time + t });
			if (time == i) {
				time++;
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[2,2,0,2,1,2]"),
				this.assignTasks(H.str2array3("[3,3,2]"), H.str2array3("[1,2,3,2,1,2]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
